const fs = require('fs')
const fsutil = require('./lib/fsutil');
const path = require('path')
const sheet = require('./lib/sheet')
const packages = [];
let _callback = null

// 重命名.  texturemerge打包  修改成pixi.js支持的sheet格式
module.exports = function(source, target, callback) {
    _callback = callback;
    const files = fs.readdirSync(source)
    packages.length = 0;
    for (let i = 0; i < files.length; i++) {
        let file = files[i];
        if (file.indexOf(".") > 0) {
            continue;
        } else {
            rename(source, file)
            packages.push(source, target, file);
        }
    }
    packages.push(target)
    generateSheet();
}

function generateSheet() {
    if (packages.length > 1) {
        let source = packages.shift();
        let target = packages.shift();
        let file = packages.shift();
        let sourceFiles = path.resolve(source, file);
        let outputFile = path.resolve(target, file + ".json");
        sheet(sourceFiles, outputFile).then(()=>{
            console.log("打包成功", outputFile);
            fs.copyFileSync(outputFile, path.join(source, `../assets/sheet/${file}.json`))
            generateSheet();
        }, ()=>{
            console.log("打包失败", sourceFiles, outputFile)
        })
    } else {
        if (packages.length == 1) {
            console.log("打包完成~~~")
            let source = packages.shift();
            updateJsons(source)
            if (_callback) {
                _callback();
            }
        } else {

        }
    }
}

// 修改egret打包的文件
function updateJsons(source) {
    let files = fs.readdirSync(source);
    for (let i = 0; i < files.length; i++) {
        let file = files[i]
        let extname = path.extname(file);
        if (extname == ".json") {
            let name = path.basename(file, ".json");
            let content = fs.readFileSync(path.join(source, file));
            let json = JSON.parse(content);
            if (json.frames) {
                let frames = {

                }
                let keys = Object.keys(json.frames);
                for (let j = 0; j < keys.length; j++) {
                    let key = keys[j];
                    let newKey = key;
                    if (newKey.indexOf(name) != 0) {
                        newKey = name + "_" + key;
                    }
                    newKey = newKey.replace("_png", ".png")
                    let item = praseItem(json.frames[key]);
                    frames[newKey] = item;
                }

                let meta = {
                    app:"node tools/generate_sheet.js",
                    version: "1.0",
                    image: `${name}.png`,
                    format: "RGBA8888"
                };
                let sheet = {frames, meta}
                fs.writeFileSync(path.join(source, file), JSON.stringify(sheet, null, 2))
            }
        }
    }
}

function praseItem(item) {
    let result = {};
    result.frame = {x:item.x, y:item.y, w:item.w, h:item.h}
    result.spriteSourceSize = {x:item.offX, y:item.offY, w:item.sourceW, h:item.sourceH}
    result.trim = result.spriteSourceSize.x || result.spriteSourceSize.y
    return result;
}

function rename(resource, file) {
    let list = [];
    fsutil.travel(path.join(resource, file), list);
    list = list.filter((name)=>{return name.indexOf(".png") > 0})
    for (let i = 0; i < list.length; i++) {
        let basename = path.basename(list[i], ".png");
        if (basename.indexOf(file + "_") < 0) {
            let oldPath = list[i];
            let newPath = path.join(path.dirname(list[i]), file + "_" + basename + ".png");
            fs.renameSync(oldPath, newPath)
        }
    }
}

